#coding=utf-8
from __future__ import unicode_literals
import requests
from bs4 import BeautifulSoup
from wxpy import *
import pymysql
import sys,io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header

def get_html(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    }
    response = requests.get(url, headers = headers)
    if response.status_code == 200:
        return response.text
    else:
        print('无数据！')
    return None

# 解析网页内容
def parse_html(html):
    soup = BeautifulSoup(html, 'lxml')
    i = 0
    for item in soup.select('tr')[2:3]:
        yield{
            'time':item.select('td')[i].text,
            'issue':item.select('td')[i+1].text,
            'red_1':item.select('td em')[0].text,
            'red_2':item.select('td em')[1].text,
            'red_3':item.select('td em')[2].text,
            'red_4': item.select('td em')[3].text,
            'red_5': item.select('td em')[4].text,
            'red_6': item.select('td em')[5].text,
            'blue': item.select('td em')[6].text,
            'First_prize_num': item.select('td')[i+4].text,
            'Sec_prize_num': item.select('td')[i+5].text,
        }

# 将数据写入excel表
def get_info():

    url = 'http://kaijiang.500.com/shtml/dlt/'
    #html = get_html(url)
    #print(html)
    html = get_html(url)
    #response = requests.get(url).text
    soup = BeautifulSoup(html, 'lxml')
    issue = soup.select('tr')[4].select('strong')[0].text
    #print(soup.select('tr')[5:6][0].select('li')[0].text)
    red_1 = soup.select('tr')[5:6][0].select('li')[0].text
    red_2 = soup.select('tr')[5:6][0].select('li')[1].text
    red_3 = soup.select('tr')[5:6][0].select('li')[2].text
    red_4 = soup.select('tr')[5:6][0].select('li')[3].text
    red_5 = soup.select('tr')[5:6][0].select('li')[4].text
    blue_1 = soup.select('tr')[5:6][0].select('li')[5].text
    blue_2 = soup.select('tr')[5:6][0].select('li')[6].text

    red_balls = [int(red_1),int(red_2),int(red_3),int(red_4),int(red_5)]
    blue_balls = [int(blue_1),int(blue_2)]

    #print(red_balls)
    #print(blue_balls)
    list_info = []
    list_info.extend(['期号: '+issue,'红球: '+str(red_balls),'蓝球: '+str(blue_balls)])
    #print(list_info)
    return list_info  


def compare_data():

    issue = get_info()[0].split(':')[1]
    #print(issue)

    #connect to database
    database = pymysql.connect(host='localhost', user='root', passwd='', db='lottery', charset='utf8')
    cursor = database.cursor()

    #check red ball
    cursor.execute('select front from dlt_my where issue='+str(issue))
    red_db = cursor.fetchone()
    if red_db:
        red_my = list(red_db)[0]
        print('我所选的红球： '+red_my)
    else:
        print('本期没有购买，错失几千万 ！！！')

    cursor.execute('select back from dlt_my where issue='+str(issue))
    blue_db = cursor.fetchone()
    if blue_db:
        blue_my = list(blue_db)[0]
        print('我所选的蓝球： '+blue_my)

    cursor.close()
    database.commit()
    database.close()

    #if red_my:
    if red_db:
        list_red_my = eval((red_my))
        list_red_official = eval(get_info()[1].split(':')[1].strip())
        list_blue_my = eval((blue_my)) 
        list_blue_official = eval(get_info()[2].split(':')[1].strip())

        red_common_num = set(list_red_my).intersection(set(list_red_official))
        blue_common_num = set(list_blue_my).intersection(set(list_blue_official))

        if len(red_common_num) == 5 and len(blue_common_num) == 2:
            print("中奖情况：5 红，2 蓝")
            messages_return = 'dlt我靠，清醒清醒！！！ 一等奖！！！！！！5 红，2 蓝'
        elif len(red_common_num) == 5 and len(blue_common_num) == 1:
            print("中奖情况：5 红，1 蓝")
            messages_return = 'dlt二等奖！！！仔细查看！！！！！！5 红，1 蓝'
        elif len(red_common_num) == 5 and len(blue_common_num)  == 0:
            print("中奖情况：5 红，0 蓝")
            messages_return = 'dlt三等奖1万元！！！仔细查看！！！！！！5 红，0 蓝'
        elif len(red_common_num) == 4 and len(blue_common_num) == 2:
            print("中奖情况：4 红，2 蓝")
            messages_return = 'dlt四等奖三千元！！！仔细查看！！！！！！4 红，2 蓝'
        elif len(red_common_num) == 4 and len(blue_common_num) == 1:
            print("中奖情况：4 红，1 蓝")
            messages_return = 'dlt五等奖300元！！！仔细查看！！！！！！4 红，1 蓝'
        elif len(red_common_num) == 3 and len(blue_common_num) == 2:
            print("中奖情况：3 红，2 蓝")
            messages_return = 'dlt六等奖200元！！！仔细查看！！！！！！3 红，2 蓝'
        elif len(red_common_num) == 4 and len(blue_common_num) == 0:
            print("中奖情况：4 红，0 蓝")
            messages_return = 'dlt七等奖100元！！！仔细查看！！！！！！4 红，0 蓝'
        elif len(red_common_num) == 3 and len(blue_common_num) == 1 :
            print("中奖情况：3 红，1 蓝")
            messages_return = 'dlt八等奖15元！！！仔细查看！！！！！！3 红，1 蓝'
        elif len(red_common_num) == 2 and len(blue_common_num) == 2 :
            print("中奖情况：2 红，2 蓝")
            messages_return = 'dlt八等奖15元！！！仔细查看！！！！！！2 红，2 蓝'
        elif len(red_common_num) == 3 and len(blue_common_num) == 0 :
            print("中奖情况：3 红，0 蓝")
            messages_return = 'dlt九等奖5元！！！仔细查看！！！！！！3 红，0 蓝'
        elif len(red_common_num) == 2 and len(blue_common_num) == 1 :
            print("中奖情况：2 红，1 蓝")
            messages_return = 'dlt九等奖5元！！！仔细查看！！！！！！2 红，1 蓝'
        elif len(red_common_num) == 1 and len(blue_common_num) == 2 :
            print("中奖情况：1 红，2 蓝")
            messages_return = 'dlt九等奖5元！！！仔细查看！！！！！！1 红，2 蓝'
        elif len(red_common_num) == 0 and len(blue_common_num) == 2 :
            print("中奖情况：0 红，2 蓝")
            messages_return = 'dlt九等奖5元！！！仔细查看！！！！！！0 红，2 蓝'
        else:
            print("中奖情况："+ str(len(red_common_num)) +" 红, "+ str(len(blue_common_num))+"  蓝")
            print("胜败乃兵家常事，大侠请重新再来！")
            messages_return = 'dlt胜败乃兵家常事，大侠请重新再来！'+ str(len(red_common_num)) +" 红, "+ str(len(blue_common_num))+"  蓝"
        return messages_return

    else:
        print("本期没有购买，错失几千万 ！！！")
        messages_return ='dlt本期没有购买，错失几千万 ！！！'
        return messages_return

def SendEmail():
    #compare_data()
    print ('Send Email to me ~~~')

    mail_host='smtp.163.com'
    mail_user='baiyflf1987'
    mail_pass='KZXVIDUHEBQLSISE'

    sender = 'baiyflf1987@163.com'
    receivers = ['421581400@qq.com']

    message = MIMEText(str(get_info()), 'plain', 'utf-8')
    message['From'] = "baiyflf1987<baiyflf1987@163.com>"
    message['To'] =  "421581400<421581400@qq.com>"

    subject = compare_data()
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host,25)
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(sender, receivers,message.as_string())
        print ('Email send successfully ~')

    except smtplib.SMTPException as e:
        print(e)
        print ('ERROR: Email send failed !!! Please double check !!!')

def main():
    #get_info()
#    compare_data()
    SendEmail()
if __name__ == '__main__':
    main()

